home *** CD-ROM | disk | FTP | other *** search
/ MacFormat 1995 January / macformat-020.iso / Shareware City / Developers / bison-1.22 / bison.info-3 < prev    next >
Encoding:
Text File  |  1992-09-08  |  48.1 KB  |  1,263 lines  |  [TEXT/EMAC]

  1. Info file bison.info, produced by Makeinfo, -*- Text -*- from input
  2. file bison.texinfo.
  3.  
  4.    This file documents the Bison parser generator.
  5.  
  6.    Copyright (C) 1988, 1989, 1990 Free Software Foundation, Inc.
  7.  
  8.    Permission is granted to make and distribute verbatim copies of
  9. this manual provided the copyright notice and this permission notice
  10. are preserved on all copies.
  11.  
  12.    Permission is granted to copy and distribute modified versions of
  13. this manual under the conditions for verbatim copying, provided also
  14. that the sections entitled "GNU General Public License" and
  15. "Conditions for Using Bison" are included exactly as in the original,
  16. and provided that the entire resulting derived work is distributed
  17. under the terms of a permission notice identical to this one.
  18.  
  19.    Permission is granted to copy and distribute translations of this
  20. manual into another language, under the above conditions for modified
  21. versions, except that the sections entitled "GNU General Public
  22. License", "Conditions for Using Bison" and this permission notice may
  23. be included in translations approved by the Free Software Foundation
  24. instead of in the original English.
  25.  
  26. 
  27. File: bison.info,  Node: Type Decl,  Next: Expect Decl,  Prev: Union Decl,  Up: Declarations
  28.  
  29. Nonterminal Symbols
  30. -------------------
  31.  
  32. When you use `%union' to specify multiple value types, you must
  33. declare the value type of each nonterminal symbol for which values are
  34. used.  This is done with a `%type' declaration, like this:
  35.  
  36.      %type <TYPE> NONTERMINAL...
  37.  
  38. Here NONTERMINAL is the name of a nonterminal symbol, and TYPE is the
  39. name given in the `%union' to the alternative that you want (*note
  40. Union Decl::.).  You can give any number of nonterminal symbols in the
  41. same `%type' declaration, if they have the same value type.  Use
  42. spaces to separate the symbol names.
  43.  
  44. 
  45. File: bison.info,  Node: Expect Decl,  Next: Start Decl,  Prev: Type Decl,  Up: Declarations
  46.  
  47. Suppressing Conflict Warnings
  48. -----------------------------
  49.  
  50.    Bison normally warns if there are any conflicts in the grammar
  51. (*note Shift/Reduce::.), but most real grammars have harmless
  52. shift/reduce conflicts which are resolved in a predictable way and
  53. would be difficult to eliminate.  It is desirable to suppress the
  54. warning about these conflicts unless the number of conflicts changes. 
  55. You can do this with the `%expect' declaration.
  56.  
  57.    The declaration looks like this:
  58.  
  59.      %expect N
  60.  
  61.    Here N is a decimal integer.  The declaration says there should be
  62. no warning if there are N shift/reduce conflicts and no reduce/reduce
  63. conflicts.  The usual warning is given if there are either more or
  64. fewer conflicts, or if there are any reduce/reduce conflicts.
  65.  
  66.    In general, using `%expect' involves these steps:
  67.  
  68.    * Compile your grammar without `%expect'.  Use the `-v' option to
  69.      get a verbose list of where the conflicts occur.  Bison will also
  70.      print the number of conflicts.
  71.  
  72.    * Check each of the conflicts to make sure that Bison's default
  73.      resolution is what you really want.  If not, rewrite the grammar
  74.      and go back to the beginning.
  75.  
  76.    * Add an `%expect' declaration, copying the number N from the
  77.      number which Bison printed.
  78.  
  79.    Now Bison will stop annoying you about the conflicts you have
  80. checked, but it will warn you again if changes in the grammer result
  81. in additional conflicts.
  82.  
  83. 
  84. File: bison.info,  Node: Start Decl,  Next: Pure Decl,  Prev: Expect Decl,  Up: Declarations
  85.  
  86. The Start-Symbol
  87. ----------------
  88.  
  89.    Bison assumes by default that the start symbol for the grammar is
  90. the first nonterminal specified in the grammar specification section. 
  91. The programmer may override this restriction with the `%start'
  92. declaration as follows:
  93.  
  94.      %start SYMBOL
  95.  
  96. 
  97. File: bison.info,  Node: Pure Decl,  Next: Decl Summary,  Prev: Start Decl,  Up: Declarations
  98.  
  99. A Pure (Reentrant) Parser
  100. -------------------------
  101.  
  102.    A "reentrant" program is one which does not alter in the course of
  103. execution; in other words, it consists entirely of "pure" (read-only)
  104. code.  Reentrancy is important whenever asynchronous execution is
  105. possible; for example, a nonreentrant program may not be safe to call
  106. from a signal handler.  In systems with multiple threads of control, a
  107. nonreentrant program must be called only within interlocks.
  108.  
  109.    The Bison parser is not normally a reentrant program, because it
  110. uses statically allocated variables for communication with `yylex'. 
  111. These variables include `yylval' and `yylloc'.
  112.  
  113.    The Bison declaration `%pure_parser' says that you want the parser
  114. to be reentrant.  It looks like this:
  115.  
  116.      %pure_parser
  117.  
  118.    The effect is that the two communication variables become local
  119. variables in `yyparse', and a different calling convention is used for
  120. the lexical analyzer function `yylex'.  *Note Pure Calling::, for the
  121. details of this.  The variable `yynerrs' also becomes local in
  122. `yyparse' (*note Error Reporting::.).  The convention for calling
  123. `yyparse' itself is unchanged.
  124.  
  125. 
  126. File: bison.info,  Node: Decl Summary,  Prev: Pure Decl,  Up: Declarations
  127.  
  128. Bison Declaration Summary
  129. -------------------------
  130.  
  131.    Here is a summary of all Bison declarations:
  132.  
  133. `%union'
  134.      Declare the collection of data types that semantic values may have
  135.      (*note Union Decl::.).
  136.  
  137. `%token'
  138.      Declare a terminal symbol (token type name) with no precedence or
  139.      associativity specified (*note Token Decl::.).
  140.  
  141. `%right'
  142.      Declare a terminal symbol (token type name) that is
  143.      right-associative (*note Precedence Decl::.).
  144.  
  145. `%left'
  146.      Declare a terminal symbol (token type name) that is
  147.      left-associative (*note Precedence Decl::.).
  148.  
  149. `%nonassoc'
  150.      Declare a terminal symbol (token type name) that is nonassociative
  151.      (using it in a way that would be associative is a syntax error)
  152.      (*note Precedence Decl::.).
  153.  
  154. `%type'
  155.      Declare the type of semantic values for a nonterminal symbol
  156.      (*note Type Decl::.).
  157.  
  158. `%start'
  159.      Specify the grammar's start symbol (*note Start Decl::.).
  160.  
  161. `%expect'
  162.      Declare the expected number of shift-reduce conflicts (*note
  163.      Expect Decl::.).
  164.  
  165. `%pure_parser'
  166.      Request a pure (reentrant) parser program (*note Pure Decl::.).
  167.  
  168. 
  169. File: bison.info,  Node: Multiple Parsers,  Prev: Declarations,  Up: Grammar File
  170.  
  171. Multiple Parsers in the Same Program
  172. ====================================
  173.  
  174.    Most programs that use Bison parse only one language and therefore
  175. contain only one Bison parser.  But what if you want to parse more
  176. than one language with the same program?  Then you need to avoid a
  177. name conflict between different definitions of `yyparse', `yylval',
  178. and so on.
  179.  
  180.    The easy way to do this is to use the option `-p PREFIX' (*note
  181. Invocation::.).  This renames the interface functions and variables of
  182. the Bison parser to start with PREFIX instead of `yy'.  You can use
  183. this to give each parser distinct names that do not conflict.
  184.  
  185.    The precise list of symbols renamed is `yyparse', `yylex',
  186. `yyerror', `yylval', `yychar' and `yydebug'.  For example, if you use
  187. `-p c', the names become `cparse', `clex', and so on.
  188.  
  189.    *All the other variables and macros associated with Bison are not
  190. renamed.* These others are not global; there is no conflict if the same
  191. name is used in different parsers.  For example, `YYSTYPE' is not
  192. renamed, but defining this in different ways in different parsers
  193. causes no trouble (*note Value Type::.).
  194.  
  195.    The `-p' option works by adding macro definitions to the beginning
  196. of the parser source file, defining `yyparse' as `PREFIXparse', and so
  197. on.  This effectively substitutes one name for the other in the entire
  198. parser file.
  199.  
  200. 
  201. File: bison.info,  Node: Interface,  Next: Algorithm,  Prev: Grammar File,  Up: Top
  202.  
  203. Parser C-Language Interface
  204. ***************************
  205.  
  206.    The Bison parser is actually a C function named `yyparse'.  Here we
  207. describe the interface conventions of `yyparse' and the other
  208. functions that it needs to use.
  209.  
  210.    Keep in mind that the parser uses many C identifiers starting with
  211. `yy' and `YY' for internal purposes.  If you use such an identifier
  212. (aside from those in this manual) in an action or in additional C code
  213. in the grammar file, you are likely to run into trouble.
  214.  
  215. * Menu:
  216.  
  217. * Parser Function:: How to call `yyparse' and what it returns.
  218. * Lexical::         You must supply a function `yylex' which reads tokens.
  219. * Error Reporting:: You must supply a function `yyerror'.
  220. * Action Features:: Special features for use in actions.
  221.  
  222. 
  223. File: bison.info,  Node: Parser Function,  Next: Lexical,  Prev: Interface,  Up: Interface
  224.  
  225. The Parser Function `yyparse'
  226. =============================
  227.  
  228.    You call the function `yyparse' to cause parsing to occur.  This
  229. function reads tokens, executes actions, and ultimately returns when it
  230. encounters end-of-input or an unrecoverable syntax error.  You can also
  231. write an action which directs `yyparse' to return immediately without
  232. reading further.
  233.  
  234.    The value returned by `yyparse' is 0 if parsing was successful
  235. (return is due to end-of-input).
  236.  
  237.    The value is 1 if parsing failed (return is due to a syntax error).
  238.  
  239.    In an action, you can cause immediate return from `yyparse' by using
  240. these macros:
  241.  
  242. `YYACCEPT'
  243.      Return immediately with value 0 (to report success).
  244.  
  245. `YYABORT'
  246.      Return immediately with value 1 (to report failure).
  247.  
  248. 
  249. File: bison.info,  Node: Lexical,  Next: Error Reporting,  Prev: Parser Function,  Up: Interface
  250.  
  251. The Lexical Analyzer Function `yylex'
  252. =====================================
  253.  
  254.    The "lexical analyzer" function, `yylex', recognizes tokens from
  255. the input stream and returns them to the parser.  Bison does not create
  256. this function automatically; you must write it so that `yyparse' can
  257. call it.  The function is sometimes referred to as a lexical scanner.
  258.  
  259.    In simple programs, `yylex' is often defined at the end of the Bison
  260. grammar file.  If `yylex' is defined in a separate source file, you
  261. need to arrange for the token-type macro definitions to be available
  262. there.  To do this, use the `-d' option when you run Bison, so that it
  263. will write these macro definitions into a separate header file
  264. `NAME.tab.h' which you can include in the other source files that need
  265. it.  *Note Invocation::.
  266.  
  267. * Menu:
  268.  
  269. * Calling Convention::   How `yyparse' calls `yylex'.
  270. * Token Values::         How `yylex' must return the semantic value
  271.                            of the token it has read.
  272. * Token Positions::      How `yylex' must return the text position
  273.                            (line number, etc.) of the token, if the
  274.                            actions want that.
  275. * Pure Calling::         How the calling convention differs
  276.                            in a pure parser (*note Pure Decl::.).
  277.  
  278. 
  279. File: bison.info,  Node: Calling Convention,  Next: Token Values,  Prev: Lexical,  Up: Lexical
  280.  
  281. Calling Convention for `yylex'
  282. ------------------------------
  283.  
  284.    The value that `yylex' returns must be the numeric code for the type
  285. of token it has just found, or 0 for end-of-input.
  286.  
  287.    When a token is referred to in the grammar rules by a name, that
  288. name in the parser file becomes a C macro whose definition is the
  289. proper numeric code for that token type.  So `yylex' can use the name
  290. to indicate that type.  *Note Symbols::.
  291.  
  292.    When a token is referred to in the grammar rules by a character
  293. literal, the numeric code for that character is also the code for the
  294. token type.  So `yylex' can simply return that character code.  The
  295. null character must not be used this way, because its code is zero and
  296. that is what signifies end-of-input.
  297.  
  298.    Here is an example showing these things:
  299.  
  300.      yylex ()
  301.      {
  302.        ...
  303.        if (c == EOF)     /* Detect end of file. */
  304.          return 0;
  305.        ...
  306.        if (c == '+' || c == '-')
  307.          return c;      /* Assume token type for `+' is '+'. */
  308.        ...
  309.        return INT;      /* Return the type of the token. */
  310.        ...
  311.      }
  312.  
  313. This interface has been designed so that the output from the `lex'
  314. utility can be used without change as the definition of `yylex'.
  315.  
  316. 
  317. File: bison.info,  Node: Token Values,  Next: Token Positions,  Prev: Calling Convention,  Up: Lexical
  318.  
  319. Semantic Values of Tokens
  320. -------------------------
  321.  
  322.    In an ordinary (nonreentrant) parser, the semantic value of the
  323. token must be stored into the global variable `yylval'.  When you are
  324. using just one data type for semantic values, `yylval' has that type. 
  325. Thus, if the type is `int' (the default), you might write this in
  326. `yylex':
  327.  
  328.      ...
  329.        yylval = value;  /* Put value onto Bison stack. */
  330.        return INT;      /* Return the type of the token. */
  331.        ...
  332.  
  333.    When you are using multiple data types, `yylval''s type is a union
  334. made from the `%union' declaration (*note Union Decl::.).  So when you
  335. store a token's value, you must use the proper member of the union. 
  336. If the `%union' declaration looks like this:
  337.  
  338.      %union {
  339.        int intval;
  340.        double val;
  341.        symrec *tptr;
  342.      }
  343.  
  344. then the code in `yylex' might look like this:
  345.  
  346.      ...
  347.        yylval.intval = value; /* Put value onto Bison stack. */
  348.        return INT;          /* Return the type of the token. */
  349.        ...
  350.  
  351. 
  352. File: bison.info,  Node: Token Positions,  Next: Pure Calling,  Prev: Token Values,  Up: Lexical
  353.  
  354. Textual Positions of Tokens
  355. ---------------------------
  356.  
  357.    If you are using the `@N'-feature (*note Action Features::.) in
  358. actions to keep track of the textual locations of tokens and groupings,
  359. then you must provide this information in `yylex'.  The function
  360. `yyparse' expects to find the textual location of a token just parsed
  361. in the global variable `yylloc'.  So `yylex' must store the proper
  362. data in that variable.  The value of `yylloc' is a structure and you
  363. need only initialize the members that are going to be used by the
  364. actions.  The four members are called `first_line', `first_column',
  365. `last_line' and `last_column'.  Note that the use of this feature
  366. makes the parser noticeably slower.
  367.  
  368.    The data type of `yylloc' has the name `YYLTYPE'.
  369.  
  370. 
  371. File: bison.info,  Node: Pure Calling,  Prev: Token Positions,  Up: Lexical
  372.  
  373. Calling for Pure Parsers
  374. ------------------------
  375.  
  376.    When you use the Bison declaration `%pure_parser' to request a pure,
  377. reentrant parser, the global communication variables `yylval' and
  378. `yylloc' cannot be used.  (*Note Pure Decl::.)  In such parsers the
  379. two global variables are replaced by pointers passed as arguments to
  380. `yylex'.  You must declare them as shown here, and pass the
  381. information back by storing it through those pointers.
  382.  
  383.      yylex (lvalp, llocp)
  384.           YYSTYPE *lvalp;
  385.           YYLTYPE *llocp;
  386.      {
  387.        ...
  388.        *lvalp = value;  /* Put value onto Bison stack.  */
  389.        return INT;      /* Return the type of the token.  */
  390.        ...
  391.      }
  392.  
  393.    If the grammar file does not use the `@' constructs to refer to
  394. textual positions, then the type `YYLTYPE' will not be defined.  In
  395. this case, omit the second argument; `yylex' will be called with only
  396. one argument.
  397.  
  398. 
  399. File: bison.info,  Node: Error Reporting,  Next: Action Features,  Prev: Lexical,  Up: Interface
  400.  
  401. The Error Reporting Function `yyerror'
  402. ======================================
  403.  
  404.    The Bison parser detects a "parse error" or "syntax error" whenever
  405. it reads a token which cannot satisfy any syntax rule.  A action in
  406. the grammar can also explicitly proclaim an error, using the macro
  407. `YYERROR' (*note Action Features::.).
  408.  
  409.    The Bison parser expects to report the error by calling an error
  410. reporting function named `yyerror', which you must supply.  It is
  411. called by `yyparse' whenever a syntax error is found, and it receives
  412. one argument.  For a parse error, the string is always `"parse error"'.
  413.  
  414.    The parser can detect one other kind of error: stack overflow.  This
  415. happens when the input contains constructions that are very deeply
  416. nested.  It isn't likely you will encounter this, since the Bison
  417. parser extends its stack automatically up to a very large limit.  But
  418. if overflow happens, `yyparse' calls `yyerror' in the usual fashion,
  419. except that the argument string is `"parser stack overflow"'.
  420.  
  421.    The following definition suffices in simple programs:
  422.  
  423.      yyerror (s)
  424.           char *s;
  425.      {
  426.  
  427.           fprintf (stderr, "%s\n", s);
  428.      }
  429.  
  430.    After `yyerror' returns to `yyparse', the latter will attempt error
  431. recovery if you have written suitable error recovery grammar rules
  432. (*note Error Recovery::.).  If recovery is impossible, `yyparse' will
  433. immediately return 1.
  434.  
  435.    The variable `yynerrs' contains the number of syntax errors
  436. encountered so far.  Normally this variable is global; but if you
  437. request a pure parser (*note Pure Decl::.) then it is a local variable
  438. which only the actions can access.
  439.  
  440. 
  441. File: bison.info,  Node: Action Features,  Prev: Error Reporting,  Up: Interface
  442.  
  443. Special Features for Use in Actions
  444. ===================================
  445.  
  446.    Here is a table of Bison constructs, variables and macros that are
  447. useful in actions.
  448.  
  449. `$$'
  450.      Acts like a variable that contains the semantic value for the
  451.      grouping made by the current rule.  *Note Actions::.
  452.  
  453. `$N'
  454.      Acts like a variable that contains the semantic value for the Nth
  455.      component of the current rule.  *Note Actions::.
  456.  
  457. `$<TYPEALT>$'
  458.      Like `$$' but specifies alternative TYPEALT in the union
  459.      specified by the `%union' declaration.  *Note Action Types::.
  460.  
  461. `$<TYPEALT>N'
  462.      Like `$N' but specifies alternative TYPEALT in the union
  463.      specified by the `%union' declaration.  *Note Action Types::.
  464.  
  465. `YYABORT;'
  466.      Return immediately from `yyparse', indicating failure.  *Note
  467.      Parser Function::.
  468.  
  469. `YYACCEPT;'
  470.      Return immediately from `yyparse', indicating success.  *Note
  471.      Parser Function::.
  472.  
  473. `YYBACKUP (TOKEN, VALUE);'
  474.      Unshift a token.  This macro is allowed only for rules that reduce
  475.      a single value, and only when there is no look-ahead token.  It
  476.      installs a look-ahead token with token type TOKEN and semantic
  477.      value VALUE; then it discards the value that was going to be
  478.      reduced by this rule.
  479.  
  480.      If the macro is used when it is not valid, such as when there is
  481.      a look-ahead token already, then it reports a syntax error with a
  482.      message `cannot back up' and performs ordinary error recovery.
  483.  
  484.      In either case, the rest of the action is not executed.
  485.  
  486. `YYEMPTY'
  487.      Value stored in `yychar' when there is no look-ahead token.
  488.  
  489. `YYERROR;'
  490.      Cause an immediate syntax error.  This statement initiates error
  491.      recovery just as if the parser itself had detected an error;
  492.      however, it does not call `yyerror', and does not print any
  493.      message.  If you want to print an error message, call `yyerror'
  494.      explicitly before the `YYERROR;' statement.  *Note Error
  495.      Recovery::.
  496.  
  497. `YYRECOVERING'
  498.      This macro stands for an expression that has the value 1 when the
  499.      parser is recovering from a syntax error, and 0 the rest of the
  500.      time.  *Note Error Recovery::.
  501.  
  502. `yychar'
  503.      Variable containing the current look-ahead token.  (In a pure
  504.      parser, this is actually a local variable within `yyparse'.) 
  505.      When there is no look-ahead token, the value `YYEMPTY' is stored
  506.      in the variable.  *Note Look-Ahead::.
  507.  
  508. `yyclearin;'
  509.      Discard the current look-ahead token.  This is useful primarily in
  510.      error rules.  *Note Error Recovery::.
  511.  
  512. `yyerrok;'
  513.      Resume generating error messages immediately for subsequent syntax
  514.      errors.  This is useful primarily in error rules.  *Note Error
  515.      Recovery::.
  516.  
  517. `@N'
  518.      Acts like a structure variable containing information on the line
  519.      numbers and column numbers of the Nth component of the current
  520.      rule.  The structure has four members, like this:
  521.  
  522.           struct {
  523.             int first_line, last_line;
  524.             int first_column, last_column;
  525.           };
  526.  
  527.           Thus, to get the starting line number of the third component, use
  528.      `@3.first_line'.
  529.  
  530.      In order for the members of this structure to contain valid
  531.      information, you must make `yylex' supply this information about
  532.      each token.  If you need only certain members, then `yylex' need
  533.      only fill in those members.
  534.  
  535.      The use of this feature makes the parser noticeably slower.
  536.  
  537. 
  538. File: bison.info,  Node: Algorithm,  Next: Error Recovery,  Prev: Interface,  Up: Top
  539.  
  540. The Bison Parser Algorithm
  541. **************************
  542.  
  543.    As Bison reads tokens, it pushes them onto a stack along with their
  544. semantic values.  The stack is called the "parser stack".  Pushing a
  545. token is traditionally called "shifting".
  546.  
  547.    For example, suppose the infix calculator has read `1 + 5 *', with a
  548. `3' to come.  The stack will have four elements, one for each token
  549. that was shifted.
  550.  
  551.    But the stack does not always have an element for each token read. 
  552. When the last N tokens and groupings shifted match the components of a
  553. grammar rule, they can be combined according to that rule.  This is
  554. called "reduction".  Those tokens and groupings are replaced on the
  555. stack by a single grouping whose symbol is the result (left hand side)
  556. of that rule.  Running the rule's action is part of the process of
  557. reduction, because this is what computes the semantic value of the
  558. resulting grouping.
  559.  
  560.    For example, if the infix calculator's parser stack contains this:
  561.  
  562.      1 + 5 * 3
  563.  
  564. and the next input token is a newline character, then the last three
  565. elements can be reduced to 15 via the rule:
  566.  
  567.      expr: expr '*' expr;
  568.  
  569. Then the stack contains just these three elements:
  570.  
  571.      1 + 15
  572.  
  573. At this point, another reduction can be made, resulting in the single
  574. value 16.  Then the newline token can be shifted.
  575.  
  576.    The parser tries, by shifts and reductions, to reduce the entire
  577. input down to a single grouping whose symbol is the grammar's
  578. start-symbol (*note Language and Grammar::.).
  579.  
  580.    This kind of parser is known in the literature as a bottom-up
  581. parser.
  582.  
  583. * Menu:
  584.  
  585. * Look-Ahead::          Parser looks one token ahead when deciding what to do.
  586. * Shift/Reduce::        Conflicts: when either shifting or reduction is valid.
  587. * Precedence::          Operator precedence works by resolving conflicts.
  588. * Contextual Precedence:: When an operator's precedence depends on context.
  589. * Parser States::       The parser is a finite-state-machine with stack.
  590. * Reduce/Reduce::       When two rules are applicable in the same situation.
  591. * Mystery Conflicts::   Reduce/reduce conflicts that look unjustified.
  592. * Stack Overflow::      What happens when stack gets full.  How to avoid it.
  593.  
  594. 
  595. File: bison.info,  Node: Look-Ahead,  Next: Shift/Reduce,  Prev: Algorithm,  Up: Algorithm
  596.  
  597. Look-Ahead Tokens
  598. =================
  599.  
  600.    The Bison parser does *not* always reduce immediately as soon as the
  601. last N tokens and groupings match a rule.  This is because such a
  602. simple strategy is inadequate to handle most languages.  Instead, when
  603. a reduction is possible, the parser sometimes "looks ahead" at the next
  604. token in order to decide what to do.
  605.  
  606.    When a token is read, it is not immediately shifted; first it
  607. becomes the "look-ahead token", which is not on the stack.  Now the
  608. parser can perform one or more reductions of tokens and groupings on
  609. the stack, while the look-ahead token remains off to the side.  When
  610. no more reductions should take place, the look-ahead token is shifted
  611. onto the stack.  This does not mean that all possible reductions have
  612. been done; depending on the token type of the look-ahead token, some
  613. rules may choose to delay their application.
  614.  
  615.    Here is a simple case where look-ahead is needed.  These three
  616. rules define expressions which contain binary addition operators and
  617. postfix unary factorial operators (`!'), and allow parentheses for
  618. grouping.
  619.  
  620.      expr:     term '+' expr
  621.              | term
  622.              ;
  623.  
  624.      
  625.      term:     '(' expr ')'
  626.              | term '!'
  627.              | NUMBER
  628.              ;
  629.  
  630.    Suppose that the tokens `1 + 2' have been read and shifted; what
  631. should be done?  If the following token is `)', then the first three
  632. tokens must be reduced to form an `expr'.  This is the only valid
  633. course, because shifting the `)' would produce a sequence of symbols
  634. `term ')'', and no rule allows this.
  635.  
  636.    If the following token is `!', then it must be shifted immediately
  637. so that `2 !' can be reduced to make a `term'.  If instead the parser
  638. were to reduce before shifting, `1 + 2' would become an `expr'.  It
  639. would then be impossible to shift the `!' because doing so would
  640. produce on the stack the sequence of symbols `expr '!''.  No rule
  641. allows that sequence.
  642.  
  643.    The current look-ahead token is stored in the variable `yychar'. 
  644. *Note Action Features::.
  645.  
  646. 
  647. File: bison.info,  Node: Shift/Reduce,  Next: Precedence,  Prev: Look-Ahead,  Up: Algorithm
  648.  
  649. Shift/Reduce Conflicts
  650. ======================
  651.  
  652.    Suppose we are parsing a language which has if-then and if-then-else
  653. statements, with a pair of rules like this:
  654.  
  655.      if_stmt:
  656.                IF expr THEN stmt
  657.              | IF expr THEN stmt ELSE stmt
  658.              ;
  659.  
  660. (Here we assume that `IF', `THEN' and `ELSE' are terminal symbols for
  661. specific keyword tokens.)
  662.  
  663.    When the `ELSE' token is read and becomes the look-ahead token, the
  664. contents of the stack (assuming the input is valid) are just right for
  665. reduction by the first rule.  But it is also legitimate to shift the
  666. `ELSE', because that would lead to eventual reduction by the second
  667. rule.
  668.  
  669.    This situation, where either a shift or a reduction would be valid,
  670. is called a "shift/reduce conflict".  Bison is designed to resolve
  671. these conflicts by choosing to shift, unless otherwise directed by
  672. operator precedence declarations.  To see the reason for this, let's
  673. contrast it with the other alternative.
  674.  
  675.    Since the parser prefers to shift the `ELSE', the result is to
  676. attach the else-clause to the innermost if-statement, making these two
  677. inputs equivalent:
  678.  
  679.      if x then if y then win (); else lose;
  680.      
  681.      if x then do; if y then win (); else lose; end;
  682.  
  683.    But if the parser chose to reduce when possible rather than shift,
  684. the result would be to attach the else-clause to the outermost
  685. if-statement, making these two inputs equivalent:
  686.  
  687.      if x then if y then win (); else lose;
  688.      
  689.      if x then do; if y then win (); end; else lose;
  690.  
  691.    The conflict exists because the grammar as written is ambiguous:
  692. either parsing of the simple nested if-statement is legitimate.  The
  693. established convention is that these ambiguities are resolved by
  694. attaching the else-clause to the innermost if-statement; this is what
  695. Bison accomplishes by choosing to shift rather than reduce.  (It would
  696. ideally be cleaner to write an unambiguous grammar, but that is very
  697. hard to do in this case.) This particular ambiguity was first
  698. encountered in the specifications of Algol 60 and is called the
  699. "dangling `else'" ambiguity.
  700.  
  701.    To avoid warnings from Bison about predictable, legitimate
  702. shift/reduce conflicts, use the `%expect N' declaration.  There will
  703. be no warning as long as the number of shift/reduce conflicts is
  704. exactly N.  *Note Expect Decl::.
  705.  
  706. 
  707. File: bison.info,  Node: Precedence,  Next: Contextual Precedence,  Prev: Shift/Reduce,  Up: Algorithm
  708.  
  709. Operator Precedence
  710. ===================
  711.  
  712.    Another situation where shift/reduce conflicts appear is in
  713. arithmetic expressions.  Here shifting is not always the preferred
  714. resolution; the Bison declarations for operator precedence allow you
  715. to specify when to shift and when to reduce.
  716.  
  717. * Menu:
  718.  
  719. * Why Precedence::      An example showing why precedence is needed.
  720. * Using Precedence::    How to specify precedence in Bison grammars.
  721. * Precedence Examples:: How these features are used in the previous example.
  722. * How Precedence::      How they work.
  723.  
  724. 
  725. File: bison.info,  Node: Why Precedence,  Next: Using Precedence,  Prev: Precedence,  Up: Precedence
  726.  
  727. When Precedence is Needed
  728. -------------------------
  729.  
  730.    Consider the following ambiguous grammar fragment (ambiguous
  731. because the input `1 - 2 * 3' can be parsed in two different ways):
  732.  
  733.      expr:     expr '-' expr
  734.              | expr '*' expr
  735.              | expr '<' expr
  736.              | '(' expr ')'
  737.              ...
  738.              ;
  739.  
  740. Suppose the parser has seen the tokens `1', `-' and `2'; should it
  741. reduce them via the rule for the addition operator?  It depends on the
  742. next token.  Of course, if the next token is `)', we must reduce;
  743. shifting is invalid because no single rule can reduce the token
  744. sequence `- 2 )' or anything starting with that.  But if the next
  745. token is `*' or `<', we have a choice: either shifting or reduction
  746. would allow the parse to complete, but with different results.
  747.  
  748.    To decide which one Bison should do, we must consider the results. 
  749. If the next operator token OP is shifted, then it must be reduced
  750. first in order to permit another opportunity to reduce the sum.  The
  751. result is (in effect) `1 - (2 OP 3)'.  On the other hand, if the
  752. subtraction is reduced before shifting OP, the result is
  753. `(1 - 2) OP 3'.  Clearly, then, the choice of shift or reduce should
  754. depend on the relative precedence of the operators `-' and OP: `*'
  755. should be shifted first, but not `<'.
  756.  
  757.    What about input such as `1 - 2 - 5'; should this be `(1 - 2) - 5'
  758. or should it be `1 - (2 - 5)'?  For most operators we prefer the
  759. former, which is called "left association".  The latter alternative,
  760. "right association", is desirable for assignment operators.  The
  761. choice of left or right association is a matter of whether the parser
  762. chooses to shift or reduce when the stack contains `1 - 2' and the
  763. look-ahead token is `-': shifting makes right-associativity.
  764.  
  765. 
  766. File: bison.info,  Node: Using Precedence,  Next: Precedence Examples,  Prev: Why Precedence,  Up: Precedence
  767.  
  768. Specifying Operator Precedence
  769. ------------------------------
  770.  
  771.    Bison allows you to specify these choices with the operator
  772. precedence declarations `%left' and `%right'.  Each such declaration
  773. contains a list of tokens, which are operators whose precedence and
  774. associativity is being declared.  The `%left' declaration makes all
  775. those operators left-associative and the `%right' declaration makes
  776. them right-associative.  A third alternative is `%nonassoc', which
  777. declares that it is a syntax error to find the same operator twice "in
  778. a row".
  779.  
  780.    The relative precedence of different operators is controlled by the
  781. order in which they are declared.  The first `%left' or `%right'
  782. declaration in the file declares the operators whose precedence is
  783. lowest, the next such declaration declares the operators whose
  784. precedence is a little higher, and so on.
  785.  
  786. 
  787. File: bison.info,  Node: Precedence Examples,  Next: How Precedence,  Prev: Using Precedence,  Up: Precedence
  788.  
  789. Precedence Examples
  790. -------------------
  791.  
  792.    In our example, we would want the following declarations:
  793.  
  794.      %left '<'
  795.      %left '-'
  796.      %left '*'
  797.  
  798.    In a more complete example, which supports other operators as well,
  799. we would declare them in groups of equal precedence.  For example,
  800. `'+'' is declared with `'-'':
  801.  
  802.      %left '<' '>' '=' NE LE GE
  803.      %left '+' '-'
  804.      %left '*' '/'
  805.  
  806. (Here `NE' and so on stand for the operators for "not equal" and so
  807. on.  We assume that these tokens are more than one character long and
  808. therefore are represented by names, not character literals.)
  809.  
  810. 
  811. File: bison.info,  Node: How Precedence,  Prev: Precedence Examples,  Up: Precedence
  812.  
  813. How Precedence Works
  814. --------------------
  815.  
  816.    The first effect of the precedence declarations is to assign
  817. precedence levels to the terminal symbols declared.  The second effect
  818. is to assign precedence levels to certain rules: each rule gets its
  819. precedence from the last terminal symbol mentioned in the components. 
  820. (You can also specify explicitly the precedence of a rule.  *Note
  821. Contextual Precedence::.)
  822.  
  823.    Finally, the resolution of conflicts works by comparing the
  824. precedence of the rule being considered with that of the look-ahead
  825. token.  If the token's precedence is higher, the choice is to shift. 
  826. If the rule's precedence is higher, the choice is to reduce.  If they
  827. have equal precedence, the choice is made based on the associativity
  828. of that precedence level.  The verbose output file made by `-v' (*note
  829. Invocation::.) says how each conflict was resolved.
  830.  
  831.    Not all rules and not all tokens have precedence.  If either the
  832. rule or the look-ahead token has no precedence, then the default is to
  833. shift.
  834.  
  835. 
  836. File: bison.info,  Node: Contextual Precedence,  Next: Parser States,  Prev: Precedence,  Up: Algorithm
  837.  
  838. Context-Dependent Precedence
  839. ============================
  840.  
  841.    Often the precedence of an operator depends on the context.  This
  842. sounds outlandish at first, but it is really very common.  For
  843. example, a minus sign typically has a very high precedence as a unary
  844. operator, and a somewhat lower precedence (lower than multiplication)
  845. as a binary operator.
  846.  
  847.    The Bison precedence declarations, `%left', `%right' and
  848. `%nonassoc', can only be used once for a given token; so a token has
  849. only one precedence declared in this way.  For context-dependent
  850. precedence, you need to use an additional mechanism: the `%prec'
  851. modifier for rules.
  852.  
  853.    The `%prec' modifier declares the precedence of a particular rule by
  854. specifying a terminal symbol whose precedence should be used for that
  855. rule.  It's not necessary for that symbol to appear otherwise in the
  856. rule.  The modifier's syntax is:
  857.  
  858.      %prec TERMINAL-SYMBOL
  859.  
  860. and it is written after the components of the rule.  Its effect is to
  861. assign the rule the precedence of TERMINAL-SYMBOL, overriding the
  862. precedence that would be deduced for it in the ordinary way.  The
  863. altered rule precedence then affects how conflicts involving that rule
  864. are resolved (*note Precedence::.).
  865.  
  866.    Here is how `%prec' solves the problem of unary minus.  First,
  867. declare a precedence for a fictitious terminal symbol named `UMINUS'. 
  868. There are no tokens of this type, but the symbol serves to stand for
  869. its precedence:
  870.  
  871.      ...
  872.      %left '+' '-'
  873.      %left '*'
  874.      %left UMINUS
  875.  
  876.    Now the precedence of `UMINUS' can be used in specific rules:
  877.  
  878.      exp:    ...
  879.              | exp '-' exp
  880.              ...
  881.              | '-' exp %prec UMINUS
  882.  
  883. 
  884. File: bison.info,  Node: Parser States,  Next: Reduce/Reduce,  Prev: Contextual Precedence,  Up: Algorithm
  885.  
  886. Parser States
  887. =============
  888.  
  889.    The function `yyparse' is implemented using a finite-state machine. 
  890. The values pushed on the parser stack are not simply token type codes;
  891. they represent the entire sequence of terminal and nonterminal symbols
  892. at or near the top of the stack.  The current state collects all the
  893. information about previous input which is relevant to deciding what to
  894. do next.
  895.  
  896.    Each time a look-ahead token is read, the current parser state
  897. together with the type of look-ahead token are looked up in a table. 
  898. This table entry can say, "Shift the look-ahead token."  In this case,
  899. it also specifies the new parser state, which is pushed onto the top
  900. of the parser stack.  Or it can say, "Reduce using rule number N."
  901. This means that a certain of tokens or groupings are taken off the top
  902. of the stack, and replaced by one grouping.  In other words, that
  903. number of states are popped from the stack, and one new state is
  904. pushed.
  905.  
  906.    There is one other alternative: the table can say that the
  907. look-ahead token is erroneous in the current state.  This causes error
  908. processing to begin (*note Error Recovery::.).
  909.  
  910. 
  911. File: bison.info,  Node: Reduce/Reduce,  Next: Mystery Conflicts,  Prev: Parser States,  Up: Algorithm
  912.  
  913. Reduce/Reduce Conflicts
  914. =======================
  915.  
  916.    A reduce/reduce conflict occurs if there are two or more rules that
  917. apply to the same sequence of input.  This usually indicates a serious
  918. error in the grammar.
  919.  
  920.    For example, here is an erroneous attempt to define a sequence of
  921. zero or more `word' groupings.
  922.  
  923.      sequence: /* empty */
  924.                      { printf ("empty sequence\n"); }
  925.              | word
  926.                      { printf ("single word %s\n", $1); }
  927.              | sequence word
  928.                      { printf ("added word %s\n", $2); }
  929.              ;
  930.  
  931. The error is an ambiguity: there is more than one way to parse a single
  932. `word' into a `sequence'.  It could be reduced directly via the second
  933. rule.  Alternatively, nothing-at-all could be reduced into a
  934. `sequence' via the first rule, and this could be combined with the
  935. `word' using the third rule.
  936.  
  937.    You might think that this is a distinction without a difference,
  938. because it does not change whether any particular input is valid or
  939. not.  But it does affect which actions are run.  One parsing order
  940. runs the second rule's action; the other runs the first rule's action
  941. and the third rule's action.  In this example, the output of the
  942. program changes.
  943.  
  944.    Bison resolves a reduce/reduce conflict by choosing to use the rule
  945. that appears first in the grammar, but it is very risky to rely on
  946. this.  Every reduce/reduce conflict must be studied and usually
  947. eliminated.  Here is the proper way to define `sequence':
  948.  
  949.      sequence: /* empty */
  950.                      { printf ("empty sequence\n"); }
  951.              | sequence word
  952.                      { printf ("added word %s\n", $2); }
  953.              ;
  954.  
  955.    Here is another common error that yields a reduce/reduce conflict:
  956.  
  957.      sequence: /* empty */
  958.              | sequence words
  959.              | sequence redirects
  960.              ;
  961.      
  962.      words:    /* empty */
  963.              | words word
  964.              ;
  965.      
  966.      redirects:/* empty */
  967.              | redirects redirect
  968.              ;
  969.  
  970. The intention here is to define a sequence which can contain either
  971. `word' or `redirect' groupings.  The individual definitions of
  972. `sequence', `words' and `redirects' are error-free, but the three
  973. together make a subtle ambiguity: even an empty input can be parsed in
  974. infinitely many ways!
  975.  
  976.    Consider: nothing-at-all could be a `words'.  Or it could be two
  977. `words' in a row, or three, or any number.  It could equally well be a
  978. `redirects', or two, or any number.  Or it could be a `words' followed
  979. by three `redirects' and another `words'.  And so on.
  980.  
  981.    Here are two ways to correct these rules.  First, to make it a
  982. single level of sequence:
  983.  
  984.      sequence: /* empty */
  985.              | sequence word
  986.              | sequence redirect
  987.              ;
  988.  
  989.    Second, to prevent either a `words' or a `redirects' from being
  990. empty:
  991.  
  992.      sequence: /* empty */
  993.              | sequence words
  994.              | sequence redirects
  995.              ;
  996.      
  997.      words:    word
  998.              | words word
  999.              ;
  1000.      
  1001.      redirects:redirect
  1002.              | redirects redirect
  1003.              ;
  1004.  
  1005. 
  1006. File: bison.info,  Node: Mystery Conflicts,  Next: Stack Overflow,  Prev: Reduce/Reduce,  Up: Algorithm
  1007.  
  1008. Mysterious Reduce/Reduce Conflicts
  1009. ==================================
  1010.  
  1011.    Sometimes reduce/reduce conflicts can occur that don't look
  1012. warranted.  Here is an example:
  1013.  
  1014.      %token ID
  1015.      
  1016.      %%
  1017.      def:    param_spec return_spec ','
  1018.              ;
  1019.      param_spec:
  1020.                   type
  1021.              |    name_list ':' type
  1022.              ;
  1023.      return_spec:
  1024.                   type
  1025.              |    name ':' type
  1026.              ;
  1027.      type:        ID
  1028.              ;
  1029.      name:        ID
  1030.              ;
  1031.      name_list:
  1032.                   name
  1033.              |    name ',' name_list
  1034.              ;
  1035.  
  1036.    It would seem that this grammar can be parsed with only a single
  1037. token of look-ahead: when a `param_spec' is being read, an `ID' is a
  1038. `name' if a comma or colon follows, or a `type' if another `ID'
  1039. follows.  In other words, this grammar is LR(1).
  1040.  
  1041.    However, Bison, like most parser generators, cannot actually handle
  1042. all LR(1) grammars.  In this grammar, two contexts, that after an `ID'
  1043. at the beginning of a `param_spec' and likewise at the beginning of a
  1044. `return_spec', are similar enough that Bison assumes they are the
  1045. same.  They appear similar because the same set of rules would be
  1046. active--the rule for reducing to a `name' and that for reducing to a
  1047. `type'.  Bison is unable to determine at that stage of processing that
  1048. the rules would require different look-ahead tokens in the two
  1049. contexts, so it makes a single parser state for them both.  Combining
  1050. the two contexts causes a conflict later.  In parser terminology, this
  1051. occurrence means that the grammar is not LALR(1).
  1052.  
  1053.    In general, it is better to fix deficiencies than to document them.
  1054.  But this particular deficiency is intrinsically hard to fix; parser
  1055. generators that can handle LR(1) grammars are hard to write and tend to
  1056. produce parsers that are very large.  In practice, Bison is more useful
  1057. as it is now.
  1058.  
  1059.    When the problem arises, you can often fix it by identifying the two
  1060. parser states that are being confused, and adding something to make
  1061. them look distinct.  In the above example, adding one rule to
  1062. `return_spec' as follows makes the problem go away:
  1063.  
  1064.      %token BOGUS
  1065.      ...
  1066.      %%
  1067.      ...
  1068.      return_spec:
  1069.                   type
  1070.              |    name ':' type
  1071.              /* This rule is never used.  */
  1072.              |    ID BOGUS
  1073.              ;
  1074.  
  1075.    This corrects the problem because it introduces the possibility of
  1076. an additional active rule in the context after the `ID' at the
  1077. beginning of `return_spec'.  This rule is not active in the
  1078. corresponding context in a `param_spec', so the two contexts receive
  1079. distinct parser states.  As long as the token `BOGUS' is never
  1080. generated by `yylex', the added rule cannot alter the way actual input
  1081. is parsed.
  1082.  
  1083.    In this particular example, there is another way to solve the
  1084. problem: rewrite the rule for `return_spec' to use `ID' directly
  1085. instead of via `name'.  This also causes the two confusing contexts to
  1086. have different sets of active rules, because the one for `return_spec'
  1087. activates the altered rule for `return_spec' rather than the one for
  1088. `name'.
  1089.  
  1090.      param_spec:
  1091.                   type
  1092.              |    name_list ':' type
  1093.              ;
  1094.      return_spec:
  1095.                   type
  1096.              |    ID ':' type
  1097.              ;
  1098.  
  1099. 
  1100. File: bison.info,  Node: Stack Overflow,  Prev: Mystery Conflicts,  Up: Algorithm
  1101.  
  1102. Stack Overflow, and How to Avoid It
  1103. ===================================
  1104.  
  1105.    The Bison parser stack can overflow if too many tokens are shifted
  1106. and not reduced.  When this happens, the parser function `yyparse'
  1107. returns a nonzero value, pausing only to call `yyerror' to report the
  1108. overflow.
  1109.  
  1110.    By defining the macro `YYMAXDEPTH', you can control how deep the
  1111. parser stack can become before a stack overflow occurs.  Define the
  1112. macro with a value that is an integer.  This value is the maximum
  1113. number of tokens that can be shifted (and not reduced) before overflow. 
  1114. It must be a constant expression whose value is known at compile time.
  1115.  
  1116.    The stack space allowed is not necessarily allocated.  If you
  1117. specify a large value for `YYMAXDEPTH', the parser actually allocates
  1118. a small stack at first, and then makes it bigger by stages as needed. 
  1119. This increasing allocation happens automatically and silently. 
  1120. Therefore, you do not need to make `YYMAXDEPTH' painfully small merely
  1121. to save space for ordinary inputs that do not need much stack.
  1122.  
  1123.    The default value of `YYMAXDEPTH', if you do not define it, is
  1124. 10000.
  1125.  
  1126.    You can control how much stack is allocated initially by defining
  1127. the macro `YYINITDEPTH'.  This value too must be a compile-time
  1128. constant integer.  The default is 200.
  1129.  
  1130. 
  1131. File: bison.info,  Node: Error Recovery,  Next: Context Dependency,  Prev: Algorithm,  Up: Top
  1132.  
  1133. Error Recovery
  1134. **************
  1135.  
  1136.    It is not usually acceptable to have a program terminate on a parse
  1137. error.  For example, a compiler should recover sufficiently to parse
  1138. the rest of the input file and check it for errors; a calculator
  1139. should accept another expression.
  1140.  
  1141.    In a simple interactive command parser where each input is one
  1142. line, it may be sufficient to allow `yyparse' to return 1 on error and
  1143. have the caller ignore the rest of the input line when that happens
  1144. (and then call `yyparse' again).  But this is inadequate for a
  1145. compiler, because it forgets all the syntactic context leading up to
  1146. the error.  A syntax error deep within a function in the compiler
  1147. input should not cause the compiler to treat the following line like
  1148. the beginning of a source file.
  1149.  
  1150.    You can define how to recover from a syntax error by writing rules
  1151. to recognize the special token `error'.  This is a terminal symbol that
  1152. is always defined (you need not declare it) and reserved for error
  1153. handling.  The Bison parser generates an `error' token whenever a
  1154. syntax error happens; if you have provided a rule to recognize this
  1155. token in the current context, the parse can continue.
  1156.  
  1157.    For example:
  1158.  
  1159.      stmnts:  /* empty string */
  1160.              | stmnts '\n'
  1161.              | stmnts exp '\n'
  1162.              | stmnts error '\n'
  1163.  
  1164.    The fourth rule in this example says that an error followed by a
  1165. newline makes a valid addition to any `stmnts'.
  1166.  
  1167.    What happens if a syntax error occurs in the middle of an `exp'? 
  1168. The error recovery rule, interpreted strictly, applies to the precise
  1169. sequence of a `stmnts', an `error' and a newline.  If an error occurs
  1170. in the middle of an `exp', there will probably be some additional
  1171. tokens and subexpressions on the stack after the last `stmnts', and
  1172. there will be tokens to read before the next newline.  So the rule is
  1173. not applicable in the ordinary way.
  1174.  
  1175.    But Bison can force the situation to fit the rule, by discarding
  1176. part of the semantic context and part of the input.  First it discards
  1177. states and objects from the stack until it gets back to a state in
  1178. which the `error' token is acceptable.  (This means that the
  1179. subexpressions already parsed are discarded, back to the last complete
  1180. `stmnts'.)  At this point the `error' token can be shifted.  Then, if
  1181. the old look-ahead token is not acceptable to be shifted next, the
  1182. parser reads tokens and discards them until it finds a token which is
  1183. acceptable.  In this example, Bison reads and discards input until the
  1184. next newline so that the fourth rule can apply.
  1185.  
  1186.    The choice of error rules in the grammar is a choice of strategies
  1187. for error recovery.  A simple and useful strategy is simply to skip
  1188. the rest of the current input line or current statement if an error is
  1189. detected:
  1190.  
  1191.      stmnt: error ';'  /* on error, skip until ';' is read */
  1192.  
  1193.    It is also useful to recover to the matching close-delimiter of an
  1194. opening-delimiter that has already been parsed.  Otherwise the
  1195. close-delimiter will probably appear to be unmatched, and generate
  1196. another, spurious error message:
  1197.  
  1198.      primary:  '(' expr ')'
  1199.              | '(' error ')'
  1200.              ...
  1201.              ;
  1202.  
  1203.    Error recovery strategies are necessarily guesses.  When they guess
  1204. wrong, one syntax error often leads to another.  In the above example,
  1205. the error recovery rule guesses that an error is due to bad input
  1206. within one `stmnt'.  Suppose that instead a spurious semicolon is
  1207. inserted in the middle of a valid `stmnt'.  After the error recovery
  1208. rule recovers from the first error, another syntax error will be found
  1209. straightaway, since the text following the spurious semicolon is also
  1210. an invalid `stmnt'.
  1211.  
  1212.    To prevent an outpouring of error messages, the parser will output
  1213. no error message for another syntax error that happens shortly after
  1214. the first; only after three consecutive input tokens have been
  1215. successfully shifted will error messages resume.
  1216.  
  1217.    Note that rules which accept the `error' token may have actions,
  1218. just as any other rules can.
  1219.  
  1220.    You can make error messages resume immediately by using the macro
  1221. `yyerrok' in an action.  If you do this in the error rule's action, no
  1222. error messages will be suppressed.  This macro requires no arguments;
  1223. `yyerrok;' is a valid C statement.
  1224.  
  1225.    The previous look-ahead token is reanalyzed immediately after an
  1226. error.  If this is unacceptable, then the macro `yyclearin' may be
  1227. used to clear this token.  Write the statement `yyclearin;' in the
  1228. error rule's action.
  1229.  
  1230.    For example, suppose that on a parse error, an error handling
  1231. routine is called that advances the input stream to some point where
  1232. parsing should once again commence.  The next symbol returned by the
  1233. lexical scanner is probably correct.  The previous look-ahead token
  1234. ought to be discarded with `yyclearin;'.
  1235.  
  1236.    The macro `YYRECOVERING' stands for an expression that has the
  1237. value 1 when the parser is recovering from a syntax error, and 0 the
  1238. rest of the time.  A value of 1 indicates that error messages are
  1239. currently suppressed for new syntax errors.
  1240.  
  1241. 
  1242. File: bison.info,  Node: Context Dependency,  Next: Debugging,  Prev: Error Recovery,  Up: Top
  1243.  
  1244. Handling Context Dependencies
  1245. *****************************
  1246.  
  1247.    The Bison paradigm is to parse tokens first, then group them into
  1248. larger syntactic units.  In many languages, the meaning of a token is
  1249. affected by its context.  Although this violates the Bison paradigm,
  1250. certain techniques (known as "kludges") may enable you to write Bison
  1251. parsers for such languages.
  1252.  
  1253. * Menu:
  1254.  
  1255. * Semantic Tokens::     Token parsing can depend on the semantic context.
  1256. * Lexical Tie-ins::     Token parsing can depend on the syntactic context.
  1257. * Tie-in Recovery::     Lexical tie-ins have implications for how
  1258.                           error recovery rules must be written.
  1259.  
  1260.    (Actually, "kludge" means any technique that gets its job done but
  1261. is neither clean nor robust.)
  1262.  
  1263.